package com.szyjjk.controller;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.reader.UnicodeReader;

import com.mysql.fabric.xmlrpc.base.Array;
import com.szyjjk.constants.SzyjjkConstant;
import com.szyjjk.constants.SzyjjkConstantSite;
//import com.szyjjk.entity.RunDm3Basics;
import com.szyjjk.entity.RunHisData;
import com.szyjjk.entity.RunMapData;
import com.szyjjk.entity.RunMapPic;
//import com.szyjjk.entity.RunMapShp;
import com.szyjjk.entity.RunModelInfo;
import com.szyjjk.entity.RunProperty;
import com.szyjjk.service.RunMapDataService;
import com.szyjjk.util.DateUtil;
import com.szyjjk.util.FileUtil;
import com.szyjjk.util.GeoTool;
import com.szyjjk.util.HttpTool;
import com.szyjjk.util.UUIDUtils;

//import openda.OpenDaClient;
@RestController
@RequestMapping("/test")
public class Atest {
	@Value("${waterPath}")
	private String waterPath;// 水流域文件位置
	@Autowired
	private RunMapDataService runMapDataService;
	@RequestMapping("")
	@ResponseBody
	public Map<String,String> A() {
		Map<String,String> map = new HashMap<>();
//		System.out.println("" + new Date());
//		File f = new File("E:\\WateraModels\\shenzhenbay_openda\\sz\\");
//		String fileName = f.getName();
//		System.out.println("OpenDaClient-fileName:"+fileName);
//		String name ="calibrate.oda";
//		OpenDaClient.openDaClient(true, f, name);
		
		String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		String replaceAll = path.replaceAll("/szyjjk-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/", "");
		String panFu = replaceAll.substring(6, replaceAll.length());
		panFu = panFu.replaceAll("/", "\\\\\\\\");
		System.out.println("项目目录---1" + path + "---------" + panFu);
		waterPath = waterPath.replaceAll("E:", panFu);
		map.put("初始路径", path);
		map.put("替换szyjjk-0.0.1-SNAPSHOT.jar路径", replaceAll);
		map.put("替换前的盘符", "E:(项目启动后读取的模型盘符)");
		map.put("替换后的盘符", panFu+"()离线下载后项目读取模型的盘符");
		map.put("离线下载后的模型位置", waterPath);
		//参数 ：mapId
		修改数据库map坐标点();
	
		
		
		return map;
	}


	private void 修改数据库map坐标点() {
		//临时修改map数据库站点坐标  mapId
		List<String> list = new ArrayList<>();
		list.add("50e4a6e58316482fbfd197353185ff8c");
		list.add("5bc1b14c40d1441eabab37d3e37b1130");
		list.add("e8d27be620544f20b709e3e98ee7c2bc");
		
		for(int i=1;i<6;i++) {
			for (String string : list) {
				List<RunMapData> runList = runMapDataService.findByMapId("run_map_data_"+i,string);
				for (RunMapData r : runList) {
					//segment 12
					String mapSite = r.getMapSite();
					// trim =12
					String trim = mapSite.replaceAll("segment", "").trim();
					int parseInt = Integer.parseInt(trim);
					int aaa =  parseInt%520;
					if(aaa==0) {
						aaa=520;
					}
					String xy = SzyjjkConstantSite.SITE.get(aaa+"");
					
					RunMapData run = new RunMapData();
					run.setId(r.getId());
					run.setMapSiteXy(xy);
					System.err.println("表名---run_map_data_"+i+"站点:"+mapSite+"源xy:"+r.getMapSiteXy()+
							"现xy:"+xy+"--------mapId"+string+"--更新id:"+r.getId());
					runMapDataService.updateById("run_map_data_"+i,run);
				}
			}
		}
	}
	/**
	 * 测试用路径 TODO
	 */
	private static final String waterResultPath = "F:\\WateraModels\\TxtInOut\\";
	private static final String waterNydroResultPath = "F:\\WateraModels\\OMS_hydro\\hydro_model_2015\\";
	private static final String waterSBWResultPath = "C:\\Users\\Administrator\\Desktop\\WaterInput\\";
	private static final String spareFilePath = "F:\\WateraModels\\";
	private static final String hydroPath="F:\\WateraModels\\waterqualtiy_model_2015\\hydro\\";

	public static void main(String[] args) throws Exception {
		File f = new File("E:\\WateraModels\\shenzhenbay_openda\\sz\\");
		String fileName = f.getName();
//		 Results.setRunningInGui(true);
//		OpenDaApplication.runApplicationBatch(f, "calibrate.oda");
		String name ="calibrate.oda";
//		OpenDaClient.openDaClient(true, f, name);
//		
//		
//		if(true) {
//			return;
//		}

        //List<RunProperty> runPropertiesList = findProAll();
        //List<RunHisData> runHisDataLists = this.findHisDataByfileID(id);
//        if (runHisDataLists.size() != 0) {
//            //执行解析
//            //return 0;
//        }
        //读his文件(); 
    



		//制作渲染图片();
	
	
		
		//HttpTool.waterHTML("Southern");
		
		生成周报();
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//输出文本内容();
		//文本追加内容();
		//重置文本内容();
		//szbDis文件加工();
		//FileUtil.copyFile(waterNydroResultPath, newFile);
		//关于SBW_river_loads_test2数据组装();	
//		String startDateC="2020-01-02";
//		String endDateD="2020-05-26";
//		getTest2Inp(startDateC, endDateD, "test2.inp");
//		getTest2Inp(startDateC, endDateD, "test2_r.inp");
		//查询文件夹中文件总行数();
		//最佳文本();
//		  File f = new File("Z:\\modisoutput\\tf_Himiwari\\20190713_2240\\Typhoon20190713_2240_albedo_03.txt");
//		  String aaa =  "Z:\\modisoutput\\tf_Himiwari\\20190713_2240\\Typhoon20190713_2240_albedo_03.txt";
//		  String fileContent6 = FileUtil.getFileContent6(aaa);
		  
		//  System.out.println(fileContent6);
		  //cmd /c powershell  CD    E:\\WateraModels\\TxtInOut ;   E:\\WateraModels\\TxtInOut\\SWAT_64debug.exe
//		  String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//			String panFu = path.substring(1, 3);
		
//		String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//		String replaceAll = path.replaceAll("/szyjjk/target/classes/", "");
//		System.out.println(replaceAll.replaceAll("/", "\\\\"));
		//提取map数据转shp();

		//FileUtil.getFileContent2("F:\\WateraModels\\TxtInOut\\output.rch");
		//boolean transferAlpha2File = FileUtil.transferAlpha2File("E:\\WateraModels\\JPG\\Print001.jpg", "E:\\WateraModels\\白色1.png");
		
	}


		private static void 生成周报() {
			
			
			
			
			
		}

	
		private static void 制作渲染图片() {
		System.out.println("启动线程    制作渲染图片png");
		try {
			
			// 开启临时锁
		
			String cco = "D:\\WateraModels\\waterqualtiy_model_2015\\hydro\\" + "com.cco";
			String jpg = "E:\\" + "JPG\\RunTest.m";
			StringBuilder sb = new StringBuilder();
			sb.append("d3d_qp('openfile','" +"D:\\WateraModels\\waterqualtiy_model_2015\\SBW_update\\test2_r.map" + "','" + cco + "');");
			sb.append("d3d_qp('selectfield','grid');");
			sb.append("d3d_qp('quickview');");
			sb.append("d3d_qp('axeslimits');");
			List<RunMapPic> listRun = new ArrayList<>();
			
			

				// 计算 当前时间到头时间有多少值
				// 文件中小时的标记
				
				sb.append("d3d_qp('selectfield','" + "Chlfa" + "');");
				sb.append("d3d_qp('allm',1);");
				sb.append("d3d_qp('alln',1);");
				sb.append("d3d_qp('allk',0);");
				// 去掉图例

				sb.append("d3d_qp('colourbar',0);");
				// 标题为空
				sb.append("d3d_qp('title','');");

				// X轴标题为空
				sb.append("d3d_qp('xlabel','');");

				// Y轴标题为空
				sb.append("d3d_qp('ylabel','');");

				// X轴颜色
				sb.append("d3d_qp('xcolour', [ 0.9999 0.9999 0.9999 ]);");

				// Y轴颜色
				sb.append("d3d_qp('ycolour', [ 0.9999 0.9999 0.9999 ]);");
				sb.append("d3d_qp('addtoplot');");
				// RunTest_bat.m 的全路径
				String picTou =  "Chlfa";
				String pic = null;
				for (int i = 0; i < 20; i++) {
					pic = picTou + "_" + i + ".jpg";

					sb.append("d3d_qp('slider',0," + i + ");");
					sb.append("d3d_qp('printfigure','" +"D:\\" + pic
							+ "','JPG file', 2, 150, 1, 1, 1);");
				}

			
			sb.append("d3d_qp('closefigure');");
			sb.append("d3d_qp('closefile');");
			//sb.append("d3d_qp('close');");

			FileUtil.createFileOrWrite(jpg, sb.toString());
			String exeMapPicPath="D:\\WateraModels\\Delft3D\\delft3d\\delft3d_ohmw_4.01.01.rc.03\\win32\\quickplot\\bin\\d3d_qp.exe";
			String cmd = exeMapPicPath + "  " + jpg;
			Runtime rn = Runtime.getRuntime();
			//rn.exec(cmd);
			System.out.println("输出完成");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private static void 读his文件() throws FileNotFoundException, IOException {
		DecimalFormat df = new DecimalFormat("#########.#");
        DecimalFormat df1 = new DecimalFormat("#########.####");
        DataInputStream dis = null;

        // test2.his: true
        // test2.map: false
        boolean bFileType = true;
        dis = new DataInputStream(new FileInputStream("E:\\WateraModels\\shenzhenbay_openda\\work2\\efdc.his"));

        dis.skip(124);


        byte[] bParamNameTime = new byte[19];
        String sParamNameTime = "";
        dis.read(bParamNameTime);
        sParamNameTime = new String(bParamNameTime);
        Date beginTime = null;
        try {
            beginTime = HttpTool.BinarySimpDate.parse(sParamNameTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(beginTime);

        dis.skip(17);

        byte[] bVarBUf = new byte[4];
        dis.read(bVarBUf);
        int iParamSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iParamSize);

        dis.read(bVarBUf);
        int iLocationSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iLocationSize);

        String sName = "";
        byte[] bParamName = new byte[20];
        String[] sParamName = new String[iParamSize];
        for (int i = 0; i < iParamSize; i++) {
            dis.read(bParamName);
            sParamName[i] = new String(bParamName);
            sName += sParamName[i];
        }
        String[] proArrayList = sName.split("          ");
        System.out.println(sName);

        byte[] bLocationName = new byte[20];
        String[] sLocationName = new String[iLocationSize];
        sName = "";
        for (int i = 0; i < iLocationSize; i++) {
            if (bFileType) {
                dis.read(bVarBUf);
                //System.out.println(ByteBuffer.wrap(b1).order(ByteOrder.LITTLE_ENDIAN).getInt());

                dis.read(bLocationName);
                sLocationName[i] = new String(bLocationName);
                sName += sLocationName[i];
            } else {
                sLocationName[i] = "segment " + df.format(i + 1);
            }
        }

        String rsultSout = "";
        List<RunHisData> runHisDataList = new ArrayList<>();
        while (dis.available() > 0) {
            dis.read(bVarBUf);
            int secound = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginTime);
            calendar.add(Calendar.SECOND, secound);

            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            calendar.set(Calendar.YEAR, date.get(Calendar.YEAR));

            System.out.println(calendar.getTime());
            System.out.println("---------------");
            for (int i = 0; i < iLocationSize; i++) {
                rsultSout = sLocationName[i] + "\t";
                String site = sLocationName[i].substring(0, 3);
                String tier = sLocationName[i].substring(6, 7);
                for (int j = 0; j < iParamSize; j++) {
                    dis.read(bVarBUf);
                    String values = df1.format(ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getFloat());
                    RunHisData runHisData = new RunHisData();
                    runHisData.setId(HttpTool.getRandomChar(32));
                    runHisData.setHisSite(site);
                    if (!tier.contains(" ") && tier.length() != 0) {
                        runHisData.setHisTier(Integer.parseInt(tier));
                    }
                    runHisData.setHisPro(proArrayList[j]);
                    runHisData.setHisValue(values);
                    runHisData.setHisTime(calendar.getTime());
                    //runHisData.setFileid(id);
                    
                    String runSiteRo=proArrayList[j].trim();
                    System.err.println(runSiteRo);
                    
//                    for (RunProperty runProperty : runPropertiesList) {
//                        String runSiteRo=proArrayList[j].trim();
//                        if(runSiteRo.equals(runProperty.getProNameen())){
//                            runHisData.setHisRemark(runProperty.getProNamech());
//                            runHisData.setHisUnit(runProperty.getProUnit());
//                        }
//                    }
                    rsultSout += values + "\t";
                    runHisDataList.add(runHisData);
                }

            }

        }
        dis.close();
        System.out.println(runHisDataList.size());
	}


	 public static boolean transferAlpha2File(String imgSrc, String imgTarget) {
	        File file = new File(imgSrc);
	        InputStream is = null;
	        boolean result = false;
	        try {
	            is = new FileInputStream(file);
	            // 如果是MultipartFile类型，那么自身也有转换成流的方法：is = file.getInputStream();
	            BufferedImage bi = ImageIO.read(is);
	            Image image = (Image) bi;
	            ImageIcon imageIcon = new ImageIcon(image);
	            BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
	                    BufferedImage.TYPE_4BYTE_ABGR);
	            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
	            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
	            int alpha = 0;
	            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
	                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
	                    int rgb = bufferedImage.getRGB(j2, j1);
	                    int R = (rgb & 0xff0000) >> 16;
	                    int G = (rgb & 0xff00) >> 8;
	                    int B = (rgb & 0xff);
	                    if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
	                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
	                    }
	                    bufferedImage.setRGB(j2, j1, rgb);
	                }
	            }
	            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
	            result = ImageIO.write(bufferedImage, "png", new File(imgTarget));// 直接输出文件
	        } catch (Exception e) {
	            e.printStackTrace();
	            result = false;
	        } finally {
	            if (is != null) {
	                try {
	                    is.close();
	                } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                }
	            }
	        }
	        return result;
	    }

	    public static byte[] transferAlpha2Byte(String imgSrc) {
	        ByteArrayOutputStream byteArrayOutputStream = null;
	        File file = new File(imgSrc);
	        InputStream is = null;
	        byte[] result = null;
	        try {
	            is = new FileInputStream(file);
	            // 如果是MultipartFile类型，那么自身也有转换成流的方法：is = file.getInputStream();
	            BufferedImage bi = ImageIO.read(is);
	            Image image = (Image) bi;
	            ImageIcon imageIcon = new ImageIcon(image);
	            BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
	                    BufferedImage.TYPE_4BYTE_ABGR);
	            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
	            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
	            int alpha = 0;
	            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
	                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
	                    int rgb = bufferedImage.getRGB(j2, j1);

	                    int R = (rgb & 0xff0000) >> 16;
	                    int G = (rgb & 0xff00) >> 8;
	                    int B = (rgb & 0xff);
	                    if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
	                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
	                    }

	                    bufferedImage.setRGB(j2, j1, rgb);

	                }
	            }

	            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
	            byteArrayOutputStream = new ByteArrayOutputStream();
	            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);//转换成byte数组
	            result = byteArrayOutputStream.toByteArray();
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (is != null) {
	                try {
	                    is.close();
	                } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                }
	            }
	            if (byteArrayOutputStream != null) {
	                try {
	                    byteArrayOutputStream.close();
	                } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                }
	            }
	        }
	        return result;
	    }






	private static void 提取map数据转shp() throws FileNotFoundException, IOException, Exception {
		String path="F:\\WateraModels\\permanentFile\\20200709104232_test2_r.map";
        DecimalFormat df = new DecimalFormat("#########.#");
        DataInputStream dis = null;

        // test2.his: true
        // test2.map: false
        dis = new DataInputStream(new FileInputStream(path));

        dis.skip(124);


        byte[] bParamNameTime = new byte[19];
        String sParamNameTime = "";
        dis.read(bParamNameTime);
        sParamNameTime = new String(bParamNameTime);
        Date beginTime = null;
        try {
            beginTime = HttpTool.BinarySimpDate.parse(sParamNameTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(beginTime);

        dis.skip(17);

        byte[] bVarBUf = new byte[4];
        dis.read(bVarBUf);
        int iParamSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iParamSize);

        dis.read(bVarBUf);
        int iLocationSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iLocationSize);
 
        String sName = "";
        byte[] bParamName = new byte[20];
        String[] sParamName = new String[iParamSize];
        for (int i = 0; i < iParamSize; i++) {
            dis.read(bParamName);
            sParamName[i] = new String(bParamName);
            sName += sParamName[i];
        }
        String[] proArrayList = sName.split("          ");
        System.out.println(sName);

        String[] sLocationName = new String[iLocationSize];
        sName = "";
        for (int i = 0; i < iLocationSize; i++) {
        	sLocationName[i] = "segment " + df.format(i + 1);
        }

        while (dis.available() > 0) {
            dis.read(bVarBUf);
            int secound = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginTime);
            calendar.add(Calendar.SECOND, secound);

            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            calendar.set(Calendar.YEAR, date.get(Calendar.YEAR));

            System.out.println(calendar.getTime());
            System.out.println("---------------");
            List<Map<String, String>> lm = new ArrayList<>();
            Date time = calendar.getTime();
            System.out.println("时间1---"+DateUtil.dateToString2(time));
            for (int i = 0; i < iLocationSize; i++) {
        	  Map<String, String> lm1 = new HashMap<>();
        	  String  site =sLocationName[i];
        	  
        	  lm1.put("proTime", DateUtil.dateToString2(time)); 
        	  lm1.put("fileName", site); 
              System.out.println("时间---"+DateUtil.dateToString2(time));
                for (int j = 0; j < iParamSize; j++) {
                    dis.read(bVarBUf);
//                    double values = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getFloat();
//                    String fiName = proArrayList[j].replaceAll(" ", "");
//                    if(StringUtils.isNotBlank(SzyjjkConstant.SBW_MAP_CODE.get(fiName))) {
//                    	 lm1.put(fiName, df.format(values)); 
//                    }
                   
                }
                lm.add(lm1);
            }
  //          GeoTool.createShp("F:\\\\WaterInput\\a.shp", lm);

        }
        dis.close();
        
//        for (RunHisData runHisData : runHisDataList) {
//        	String dddd = DateUtil.dateToString2(runHisData.getHisTime());
//        	if("2020-07-08 00:00:00".equals(dddd)) {
//			System.out.println(runHisData.getHisPro() +"---"+""+runHisData.getHisSite()+"----"+
//					runHisData.getHisValue()+"----"+dddd);
//        	}
//		}
//		for (Map.Entry<String, List<Map<String, String>>> string : dateM.entrySet()) {
//					System.out.println(string.getKey());
//					List<Map<String,String>> value = string.getValue();
//					System.out.println(value);
//				}

//        GeoTool.createShp(path, lm);
        
	}




	private static void 最佳文本() {
		try {
			String cco=hydroPath+"com.cco";
			String jpg=spareFilePath+"JPG\\";
			String mapParam="F:\\WateraModels\\Delft3D\\"+"RunTest.m";
			//map 的位置
			String  a ="F:\\WateraModels\\permanentFile\\20200622102236_test2_r.map";
			Map<String,String> map =SzyjjkConstant.SBW_MAP_CODE;
			for(Map.Entry<String,String> m :map.entrySet()) {
				//TODO本地用value  服务器用 key
				String key = m.getKey();
				String code = m.getValue();
				
				
				String touDate = "2020-06-17 00:00:00";
				String weiDate = "2020-06-22 00:00:00";
				
				
				Date touDateD = DateUtil.stringToDate3(touDate);
				Date weiDateD = DateUtil.stringToDate3(weiDate);

				//计算 当前时间到头时间有多少值
				int dayNum = (DateUtil.getDayNum(touDateD, weiDateD));
				//文件中小时的标记
				int fileNo= (dayNum*24)+1;
				List<RunMapPic> listRun = new ArrayList<>();
				StringBuilder  sb  = new StringBuilder();
				sb.append("d3d_qp('openfile','"+a+"','"+cco+"');");
				sb.append("d3d_qp('selectfield','grid');");
				sb.append("d3d_qp('quickview');");
				sb.append("d3d_qp('axeslimits');");
				sb.append("d3d_qp('selectfield','"+code+"');");
				sb.append("d3d_qp('allm',1);");
				sb.append("d3d_qp('alln',1);");
				sb.append("d3d_qp('allk',0);");
				sb.append("d3d_qp('addtoplot');");
				//  RunTest_bat.m 的全路径
				String picTou = code+"_"+DateUtil.getDate();
				String pic = null;
				for(int i=0 ;i<fileNo;i++) {
					Date date = DateUtil.addDateMinut(new Date(), i);
					pic = picTou+"_"+i+".jpg";
					RunMapPic rmp = new RunMapPic();
					rmp.setId(UUIDUtils.getUUID());
					rmp.setFileid("1111111");
					rmp.setMapName("setMapName");
					rmp.setMapPath("setMapPath");
					rmp.setCcoPath(cco);
					rmp.setParamPath(mapParam);
					rmp.setMapValue(code);
					rmp.setMapCode(code);
					rmp.setMapDate(i+"");
					rmp.setMapTime(date);
				    rmp.setCreateTime(new Date());
				    rmp.setMapPicName(pic);
				    rmp.setMapPicPath(jpg);
					rmp.setRemake("0");
					listRun.add(rmp);
					String name  = "F:\\WateraModels\\ttttt\\"+pic;
					sb.append("d3d_qp('slider',0,"+i+");");
					sb.append("d3d_qp('printfigure','"+name+"','JPG file', 2, 150, 1, 1, 1);");
				}
				sb.append("d3d_qp('closefigure');");
				sb.append("d3d_qp('closefile');");
				sb.append("d3d_qp('close');");
				System.out.println(jpg);
				FileUtil.createFileOrWrite(mapParam, sb.toString());
				String cmd="F:\\WateraModels\\Delft3D\\delft3d\\delft3d_ohmw_4.01.01.rc.03\\win32\\quickplot\\bin\\d3d_qp.exe F:\\WateraModels\\Delft3D\\RunTest.m";
				Runtime rn = Runtime.getRuntime();
				Process p = rn.exec(cmd);
				File f = new File("F:\\WateraModels\\ttttt\\"+pic);
				int c =0;
				while(true) {
					Thread.sleep(2000);
					c++;
					if(c==150) {
						//防死
						break;
					}
					System.out.println("1111111111111111111111111");
					if(f.exists()) {
						break;
					}
				}
				
				
			}
			
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}




	private static void 查询文件夹中文件总行数() {
		int sum = 0;
		//查询代码量 行
		String pathAAA= "F:\\aaaaa\\";
		File ff = new File(pathAAA);
		File[] listFiles = ff.listFiles();
		for (int i=0; i<listFiles.length ; i++) {
			String name = listFiles[i].getName();
			String[] fileContent = FileUtil.getFileContent(pathAAA+name);
			int  a  = (Integer.parseInt(fileContent[1]))-1;
			sum=sum+a;
			System.out.println("编号："+i+"         "+name+"             "+a);
		}
		System.out.println("总行数："+sum);
	}




	private static void getTest2Inp(String startDateC, String endDateD, String fileName) {
		int row = 1;
		while (true) {
			String fileContent5 = FileUtil.getFileContent5(spareFilePath + fileName, row);
			if(row==1) {
				String substring = fileContent5.substring(0, fileContent5.length());
				substring=substring+"\r\n"+";"+"\r\n";
				FileUtil.createFileOrWrite(waterSBWResultPath + fileName, substring);
				row+=2;
				continue;
			}
			
			//开始时间
			// 2015/01/01-00:00:00      ; start time 
			if(row==83) {
				String[] cArray = startDateC.split("-");
				StringBuilder sb =new StringBuilder();
				String[] split = fileContent5.split("\\/");
				sb.append(split[0]).append("/").append(cArray[1]).append("/").append(cArray[2]).append(split[2].substring(2, split[2].length()));
				fileContent5=sb.toString();
			}
			//结束时间
			if(row==84) {
				String[] cArray = endDateD.split("-");
				StringBuilder sb =new StringBuilder();
				String[] split = fileContent5.split("\\/");
				sb.append(split[0]).append("/").append(cArray[1]).append("/").append(cArray[2]).append(split[2].substring(2, split[2].length()));
				fileContent5=sb.toString();
			}
			
			FileUtil.appendContent(waterSBWResultPath + fileName, fileContent5);
			if(row==272) {
				break;
			}
			row++;
			}
	}




	private static void 读二进制文件(String a) throws FileNotFoundException, IOException {
		DecimalFormat df = new DecimalFormat("#########.#");
        DataInputStream dis = null;

		// test2.his: true
		// test2.map: false
        boolean bFileType = false;
        dis = new DataInputStream(new FileInputStream (a));
        dis.skip(160);

        byte []bVarBUf = new byte [4];
        dis.read(bVarBUf);
        int iParamSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iParamSize);

        dis.read(bVarBUf);
        int iLocationSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
        System.out.println(iLocationSize);

        String sName = "";
        byte []bParamName = new byte [20];
        String[] sParamName = new String[iParamSize];
        for (int i = 0 ; i<iParamSize ; i++) {
            dis.read(bParamName);
            sParamName[i] = new String (bParamName);
            sName += sParamName[i];
        }
        System.out.println(sName);

        byte []bLocationName = new byte [20];
        String[] sLocationName = new String[iLocationSize];
        sName = "";
        for (int i = 0 ; i < iLocationSize ; i++) {
            if (bFileType) {
                dis.read(bVarBUf);
                //System.out.println(ByteBuffer.wrap(b1).order(ByteOrder.LITTLE_ENDIAN).getInt());

                dis.read(bLocationName);
                sLocationName[i] = new String(bLocationName);
                sName += sLocationName[i];
            }
            else {
                sLocationName[i] = "segment " + df.format(i + 1);
            }
        }
        System.out.println(sName);

        String sOut = "";
        while (dis.available() > 0){
            dis.read(bVarBUf);
            System.out.println(ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt());

            for (int i = 0 ; i < iLocationSize; i++) {
                sOut = sLocationName[i] + "\t";
                for (int j = 0 ; j < iParamSize; j++) {
                    dis.read(bVarBUf);
                    sOut += df.format(ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getFloat()) + "\t";
                }
                System.out.println(sOut);
            }
        }
	}




	private static void 关于SBW_river_loads_test2数据组装() {
		String filePath = waterResultPath + "output.rch";
		//每月一号 可能提取
		//key 1234 河流  list1 12 个月的数据  list2 一行的每个数据
		//读一行写一行
		//删除
		//创建 写入第一行
		//最佳第二行
//		for(Map.Entry<String, List<List<String>>> map:fileContent4.entrySet()) {
//			System.err.println("rch----"+map.getKey()+"集合1长度----"+map.getValue().size());
//			List<List<String>> value = map.getValue();
//			
//			for (List<String> list : value) {
//				for (String string : list) {
//					System.out.print(string+"-");
//				}
//				System.out.println();
//			}
//		}
		
		List<String> monthOfDay= Arrays.asList("1","31","61","91","121","151","181","211","241","271","301","331");
		Map<String, List<List<String>>> fileContent4 = FileUtil.getFileContent4(filePath, monthOfDay);
		DecimalFormat df = new DecimalFormat("00");
		int row=1;
		int spaceNum=0;
		String rchName="0";
		int day=0;
		double daySBW=1;
		while(true) {
			String fileContent5 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row);
			//文件读取完毕
			if(StringUtils.isBlank(fileContent5)) {
				spaceNum++;
				if(spaceNum==21) {
					break;
				}
				
			}
			//河流号
			if(row>24) {
				if(fileContent5.contains("dasha")) {
					rchName="1";
				}else if(fileContent5.contains("shenzhen")) {
					rchName="2";
				}else if(fileContent5.contains("yuanlang")) {
					rchName="3";
				}else if(fileContent5.contains("tianshuiwei")){
					rchName="4";
				}
			}
			//System.err.println("行数="+row+"   长度="+fileContent5.length()+"  内容="+fileContent5);
			
			if(row==1) {
				FileUtil.createFileOrWrite(hydroPath+"\\SBW_river_loads_test2.dat", fileContent5+"\n");
			}else {
				//判断没一行长度 获取日期		
				if(fileContent5.length()>=23) {
					String year = fileContent5.substring(0, 4);
					String touTime = fileContent5.substring(0, 10);
					String touNum = fileContent5.substring(0, 23).trim();
					//数据行 ||NumberUtils.isNumber(str)
					if(DateUtil.isDate(touTime)||NumberUtils.isNumber(touNum)) {
						//日期转天
						//int getnewYeayDay1 = DateUtil.getnewYeayDay1(DateUtil.stringToDate(touTime));
						
						if("1".equals(rchName)||"2".equals(rchName)) {
							List<List<String>> list = fileContent4.get(rchName);
							if(day>list.size()-1) {day=0;}
							
							// 一行到头"	" 18  19  'NH4'	'NO3'
							//12月
							if(daySBW>12) {
								daySBW=1;
							}
							//保留12条 源文件中14条 超出的条数跳过
							if(daySBW==12) {
								row=row+2;
							}
							List<String> list2 = list.get(day);
							//  对应一月一号  17NO3_OUTkg 19  NH4_OUTkg
							String string2 = list2.get(17);
							String string3 = list2.get(19);
							
							String NO3 = string2.substring(0, 4)+""+string2.substring(6, string2.length());
							String NH4=  string3.substring(0, 4)+""+string3.substring(6, string3.length());
							String[] split = fileContent5.split("\t");
							String format = df.format(daySBW);
							split[0]=year+"/"+format+"/01"+"-00:00:00";
							daySBW++;
							split[18]="NH4";split[19]="NO3";
							split[18]=NH4;split[19]=NO3;
							StringBuilder sb = new StringBuilder();
							for (String string : split) {
								sb.append(string);
								sb.append("\t");
							}
							FileUtil.appendContent(hydroPath+"\\SBW_river_loads_test2.dat", sb.toString());
						}else if("3".equals(rchName)||"4".equals(rchName)){

							//换行 如果头是日期  
							if(DateUtil.isDate(touTime)) {
								if(daySBW>12) {
									daySBW=1;
								}
								
								List<List<String>> list = fileContent4.get(rchName);
								if(day>list.size()-1) {day=0;}
								
								List<String> list2 = list.get(day);
								//  对应一月一号  17NO3_OUTkg 19  NH4_OUTkg
								String NH4 = list2.get(17);
								String NO3 = list2.get(19);
								
								
								String[] split = fileContent5.split("  ");
								String format = df.format(daySBW);
								split[0]=year+"/"+format+"/01"+"-00:00:00";
								daySBW++;
								StringBuilder sb = new StringBuilder();
								//sb.append(fileContent5);
								
								for (String string : split) {
									sb.append(string);
									sb.append("\t");
								}
								sb.append("\n");
								String row1 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+1);
								String row2 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+2);
								String row3 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+3);
								StringBuilder sb1 = new StringBuilder();
								String[] split2 = row3.split("  ");
								
								split2[8]=NH4;
								split2[9]=NO3;
								for (String string : split2) {
									sb1.append(string);
									sb1.append("  ");
								}
								row3=sb1.toString();
								// row3 行包括 No3 和 nh4
								String row4 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+4);
								String row5 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+5);
								String row6 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+6);
								String row7 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+7);
								String row8 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+8);
								String row9 = FileUtil.getFileContent5(spareFilePath+"SBW_river_loads_test2.dat", row+9);
								
								sb.append(row1).append("\n").append(row2).append("\n").append(row3).append("\n").append(row4)
								.append("\n").append(row5).append("\n").append(row6).append("\n").append(row7)
								.append("\n").append(row8).append("\n").append(row9);
								FileUtil.appendContent(hydroPath+"\\SBW_river_loads_test2.dat", sb.toString());
								row=row+9;
								
								if(daySBW-1==12) {
									row=row+20;
								}
							}	
						}else {
							FileUtil.appendContent(hydroPath+"\\SBW_river_loads_test2.dat", fileContent5);
						}
					}else {
						//非数据行 保持原样
						FileUtil.appendContent(hydroPath+"\\SBW_river_loads_test2.dat", fileContent5);
					}
				}else {
					//非数据行 保持原样
					FileUtil.appendContent(hydroPath+"\\SBW_river_loads_test2.dat", fileContent5);
				}
				
			}
			row++;
		}
	}

	
	
	
	

	private static void szbDis文件加工() {
		Map<String, List<String>> map = 获取output的数据并加工();
		String a = "C:\\Users\\Administrator\\Desktop\\WaterInput\\szb.dis";
		String b = "C:\\Users\\Administrator\\Desktop\\WaterInput\\aaaaaaa.dis";
		
		getRows(a, b, 1, 12);
		getRows2(a, b, 13, 26,map.get("1"));
		getRows1(a, b,27,38);
		getRows2(a, b, 39, 52,map.get("2"));
		getRows1(a, b,53,64);
		getRows2(a, b, 65, 78,map.get("3"));
		getRows1(a, b,79,90);
		getRows2(a, b,91,104,map.get("4"));
	}


	private static void getRows(String a, String b,int row1,int row2) {
		Map<Integer, String> row1_12 = FileUtil.getFileContent3(a, row1, row2);
		StringBuilder sb1 = new StringBuilder();
		for(Entry<Integer, String> m:row1_12.entrySet()) {
			System.err.println(m.getKey()+"-----"+m.getValue());
			sb1.append(m.getValue());
			sb1.append("\n");
		}
		FileUtil.createFileOrWrite(b, sb1.toString());
	}

	private static void getRows2(String a, String b,int row1,int row2,List<String> list) {
		list.add(0, list.get(0));
		list.add(list.get(list.size()-1));
		int j=0;
		StringBuilder sb = new StringBuilder();
		Map<Integer, String> row = FileUtil.getFileContent3(a, row1, row2);
		for(Entry< Integer, String> m:row.entrySet()) {
			//System.err.println(m.getKey()+"-----"+m.getValue());
			String value = m.getValue();
			String[] split = value.split(" ");
			int i=1;
			
			sb.append(" ");
			for (String string : split) {
				
				if(StringUtils.isNotBlank(string)) {

					if(i==2) {
						String str = list.get(j);
						//科学计数法 scientific(str)
						
						sb.append(scientific(str));
						j++;
					}else {
						sb.append(string);	
					}
					sb.append("  ");
					i++;
				}
			}	
			sb.append("\n");
		}
		FileUtil.appendContent(b, sb.toString().substring(0,sb.toString().length()-1));
	}

	private static String scientific(String str) {
		
		String res ="0.0000000e+000";
		double dStr = Double.parseDouble(str);
		DecimalFormat df = new DecimalFormat("#0.00");
		
		if(dStr>=1000&&dStr<10000) {
			res=df.format(dStr/1000)+"00000e+003";
		}else if(dStr>=100&&dStr<1000) {
			res=df.format(dStr/100)+"00000e+002";
		}else if(dStr>=10&&dStr<100) {
			res=df.format(dStr/10)+"00000e+001";
		}else if(dStr>=1&&dStr<10) {
			res=df.format(dStr)+"00000e+000";
		}else if(dStr>=0.1&&dStr<1) {
			res=df.format(dStr*10)+"00000e-001";
		}else if(dStr>0.01&&dStr<0.1) {
			res=df.format(dStr*100)+"00000e-002";
		}else if(dStr>0.001&&dStr<0.01) {
			res=df.format(dStr*1000)+"00000e-003";
		}else if(dStr>0.0001&&dStr<0.001) {
			res=df.format(dStr*10000)+"00000e-004";
		}else if(dStr>0.00001&&dStr<0.0001) {
			res=df.format(dStr*100000)+"00000e-005";
		}
		return res;
	}

	private static void getRows1(String a, String b,int row1,int row2) {
		StringBuilder sb = new StringBuilder();
		Map<Integer, String> row = FileUtil.getFileContent3(a, row1, row2);
		for(Entry<Integer, String> m:row.entrySet()) {
			System.err.println(m.getKey()+"-----"+m.getValue());
			sb.append(m.getValue());
			sb.append("\n");
			
		}
		FileUtil.appendContent(b, sb.toString().substring(0,sb.toString().length()-1));
	}

	private static Map<String, List<String>>  获取output的数据并加工() {
		double sum = 0;
		
		Map<String, List<String>> map = new HashMap<>();
		
		
		String a = "C:\\Users\\Administrator\\Desktop\\WaterInput\\output1.rch";
		Map<String, List<String>> fileContent2 = FileUtil.getFileContent2(a);
		for(Entry<String, List<String>> m:fileContent2.entrySet()) {
			System.err.println(m.getKey()+"----------------------");
			List<String> value = m.getValue();
			int z=0;
			int i=0;
			for (String string : value) {
				i++;
				sum+=Double.parseDouble(string);
				//System.out.println(string);
				if(i%30==0) {
					double avg = sum/30;
					
					List<String> list = map.get(m.getKey());
					if(CollectionUtils.isEmpty(list)) {
						List<String> mapList = new ArrayList<String>();
						mapList.add(avg+"");
						map.put(m.getKey(), mapList);
					}else {
						list.add(avg+"");
						map.put(m.getKey(), list);
					}
					System.err.println("--------------------------"+(z+1)+"月"+"---"+avg);
					sum=0;
					z++;
					if(z==12) {
						break;
					}
				}
			}
		}

		return map;
	}

	private static void 重置文本内容() {
		File fff = new File("C:\\Users\\Administrator\\Desktop\\WaterInput\\1111111.wnd");
		if(!fff.exists()) {
			try {
				fff.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			FileWriter fileWriter = new FileWriter("C:\\Users\\Administrator\\Desktop\\WaterInput\\1111111.wnd");
			fileWriter.write("Station  hop0pcp,hop1pcp,hop3pcp,\nStation  hop0pcp,hop1pcp,hop3pcp,");
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void 文本追加内容() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("F:\\WateraModels\\TxtInOut\\pcp1.pcp");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		
		
		
		pw.println("Station  hop0pcp,hop1pcp,hop3pcp,");
		pw.println("Lati    33.2 32.9 32.8");
		pw.println("Long   -95.6-95.7-95.9");
		pw.println("Long   -95.6-95.7-95.9");
		pw.println("Elev     150  151  133");
		pw.println("追加内容1\n追加内容2");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
			System.out.println("追加输出成功" + new Date());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void 输出文本内容() {
		String a = "F:\\TxtInOut\\Tmp1.Tmp";
		a = "C:\\Users\\Administrator\\Desktop\\WaterInput\\wnd.wnd";
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(a));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				System.out.println("line " + line + ": " + tempString.trim());
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}
	}
}
